package com.ctshk.rpc.scenic.service.impl.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ctshk.common.constant.ElasticSearchConstant;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.ChannelMainData;
import com.ctshk.rpc.scenic.dto.ScenicProductChannelOnlineSelfPlatformDTO;
import com.ctshk.rpc.scenic.dto.app.ScenicProductEsDTO;
import com.ctshk.rpc.scenic.dto.app.ScenicProductIndexDTO;
import com.ctshk.rpc.scenic.dto.app.ScenicProductTypeListDTO;
import com.ctshk.rpc.scenic.dto.app.inner.HotRecommendList;
import com.ctshk.rpc.scenic.dto.app.inner.PopularProductList;
import com.ctshk.rpc.scenic.dto.app.inner.ProductList;
import com.ctshk.rpc.scenic.entity.ScenicProductCostStrategySpecStock;
import com.ctshk.rpc.scenic.mapper.ScenicProductChannelOnlineSelfPlatformMapper;
import com.ctshk.rpc.scenic.mapper.ScenicProductCostStrategySpecStockMapper;
import com.ctshk.rpc.scenic.service.app.IScenicProductPCService;
import com.ctshk.rpc.scenic.service.app.IScenicProductTypeService;
import com.ctshk.rpc.scenic.service.app.IScenicTicketRecommendService;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author 黄先
 */
@DubboService
public class ScenicProductPCServiceImpl implements IScenicProductPCService {
    @Autowired
    RedisTemplate<String, String> redisTemplate;
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Autowired
    IScenicTicketRecommendService iScenicTicketRecommendService;

    @Autowired
    IScenicProductTypeService iScenicProductTypeService;
    @Autowired
    ScenicProductChannelOnlineSelfPlatformMapper scenicProductChannelOnlineSelfPlatformMapper;

    @Autowired
    private ScenicProductCostStrategySpecStockMapper scenicProductCostStrategySpecStockMapper;

    /**
     * 查询首页数据
     * @param channelId
     * @param cityId
     * @return
     */
    @Override
    public Result<ScenicProductIndexDTO> selectScenicProductIndex(Long channelId, Long cityId) {
        ScenicProductIndexDTO scenicProductIndexDTO = new ScenicProductIndexDTO();
        try{
            // 查询分类列表
            List<ScenicProductTypeListDTO> typeList = iScenicProductTypeService.selectScenicProductTypeList();
            scenicProductIndexDTO.setTypeList(typeList);
            {// 查询热门推荐
                if(typeList != null && typeList.size() > 0){
                    List<HotRecommendList> hotRecommendLists = scenicProductIndexDTO.getHotRecommendList();
                    for (ScenicProductTypeListDTO typeListDTO : typeList) {
                        Map<String, Object> fuzzyMap = new HashMap<>();
                        fuzzyMap.put("channelId", channelId);
                        fuzzyMap.put("cityId", cityId);
                        fuzzyMap.put("isRecommend", 1);
                        if(StringUtils.isNotEmpty(typeListDTO.getTitle())){
                            fuzzyMap.put("productTypeName.keyword", typeListDTO.getTitle());
                        }
                        SearchResponse search = search(fuzzyMap, null, 0, 7);
                        if(search != null && search.getHits().getTotalHits().value > 0){
                            SearchHits hits = search.getHits();
                            HotRecommendList hotRecommendList = new HotRecommendList();
                            hotRecommendList.setName(typeListDTO.getTitle());
                            List<ProductList> productList = hotRecommendList.getProductList();
                            for (SearchHit hit : hits) {
                                ScenicProductEsDTO scenicProductEsDTO = JSON.parseObject(hit.getSourceAsString(), ScenicProductEsDTO.class);
                                if(scenicProductEsDTO != null){
                                    ProductList productObj = new ProductList();
                                    productObj.setProductId(scenicProductEsDTO.getProductId());
                                    productObj.setTitle(scenicProductEsDTO.getProductName());
                                    productObj.setPrice(scenicProductEsDTO.getCostPrice());


                                    //成本乘以倍数，加上服务费，加上加服
                                    Double rate = scenicProductEsDTO.getExchangeRate();//汇率

                                    BigDecimal price = null;
                                    //成本乘以倍数，加上服务费，加上加服
                                    List<ScenicProductCostStrategySpecStock> stocksObj = scenicProductCostStrategySpecStockMapper.quertCostPriceByid(scenicProductEsDTO.getProductId());
                                    if (!Objects.isNull(stocksObj.get(0).getCostPrice())){
                                        //成本
                                        price = stocksObj.get(0).getCostPrice();
                                        productObj.setPrice(price);
                                    }
                                    BigDecimal mone = price.multiply(BigDecimal.valueOf(rate));
                                    productObj.setExchangeRate(scenicProductEsDTO.getExchangeRate());
                                    productObj.setReserveCharge(scenicProductEsDTO.getReserveCharge());
                                    BigDecimal pcAmount = null;
                                    BigDecimal appAmount = null;
                                    //查询加服
                                    List<ScenicProductChannelOnlineSelfPlatformDTO> platformObj = scenicProductChannelOnlineSelfPlatformMapper.selectByProductIdList(scenicProductEsDTO.getProductId());
                                    if (!Objects.isNull(platformObj)){

                                        for (ScenicProductChannelOnlineSelfPlatformDTO obj : platformObj){
                                            if (obj.getChannelId().equals(ChannelMainData.APP_H5.getId())){

                                                BigDecimal jfPrice = new BigDecimal("0");
                                                // 加幅类型
                                                Integer adjustType = obj.getAdjustType();
                                                if(adjustType != null){
                                                    if(adjustType.equals(1)){
                                                        // 指定数值
                                                        if(obj.getAmount() != null){
                                                            jfPrice = jfPrice.add(obj.getAmount());
                                                        }
                                                    }else if(adjustType.equals(2)){
                                                        // 百分比
                                                        if(obj.getAmount() != null){
                                                            jfPrice = jfPrice.add(mone.divide(obj.getAmount(), 0, BigDecimal.ROUND_UNNECESSARY).multiply(new BigDecimal("100")));
                                                        }
                                                    }
                                                }

                                                //加服
                                                appAmount = jfPrice;
                                                if (appAmount != null){
                                                    productObj.setAmount(jfPrice);
                                                    BigDecimal moneAttr = (mone.add(appAmount)).setScale(0,BigDecimal.ROUND_UP);
                                                    productObj.setAppMoney(moneAttr
                                                            .add(scenicProductEsDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP)));

                                                }else if (appAmount == null){
                                                    productObj.setAppMoney(mone.setScale(0,BigDecimal.ROUND_UP)
                                                            .add(scenicProductEsDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP)));
                                                }

                                            }else if (obj.getChannelId().equals(ChannelMainData.CHINA_TRAVEL.getId())){
                                                BigDecimal jfPrice = new BigDecimal("0");
                                                // 加幅类型
                                                Integer adjustType = obj.getAdjustType();
                                                if(adjustType != null){
                                                    if(adjustType.equals(1)){
                                                        // 指定数值
                                                        if(obj.getAmount() != null){
                                                            jfPrice = jfPrice.add(obj.getAmount());
                                                        }
                                                    }else if(adjustType.equals(2)){
                                                        // 百分比
                                                        if(obj.getAmount() != null){
                                                            jfPrice = jfPrice.add(mone.divide(obj.getAmount(), 0, BigDecimal.ROUND_UNNECESSARY).multiply(new BigDecimal("100")));
                                                        }
                                                    }
                                                }
                                                pcAmount = jfPrice;
                                                if (pcAmount != null){
                                                    BigDecimal moneAttr = (mone.add(pcAmount)).setScale(0,BigDecimal.ROUND_UP);
                                                    productObj.setPcMoney(moneAttr
                                                            .add(scenicProductEsDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP)));
                                                }else if (pcAmount == null){
                                                    productObj.setPcMoney(mone.setScale(0,BigDecimal.ROUND_UP)
                                                            .add(scenicProductEsDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP)));
                                                }

                                            }
                                            productObj.setReserveCharge(scenicProductEsDTO.getReserveCharge());
                                        }
                                    }


                                    {// 解析图片
                                        String photosJson = scenicProductEsDTO.getPhotosJson();
                                        if(photosJson != null){
                                            List<JSONObject> jsonObjects = JSON.parseArray(photosJson, JSONObject.class);
                                            if(jsonObjects != null && jsonObjects.size() > 0){
                                                JSONObject jsonObject = jsonObjects.get(0);
                                                String url = jsonObject.getString("url");
                                                if(url != null){
                                                    productObj.setPng(url);
                                                }
                                            }
                                        }
                                    }
                                    productList.add(productObj);
                                }
                            }
                            hotRecommendLists.add(hotRecommendList);
                        }
                    }
                }
            }
            {// 查询人气门票
                List<PopularProductList> popularList = scenicProductIndexDTO.getPopularList();
                Map<String, Object> fuzzyMap = new HashMap<>();
                fuzzyMap.put("channelId", channelId);
                fuzzyMap.put("cityId", cityId);
                fuzzyMap.put("isRecommend", 1);
                SearchResponse search = search(fuzzyMap, null, 0, 4);
                SearchHits hits = search.getHits();
                for (SearchHit hit : hits) {
                    PopularProductList popularProductList = new PopularProductList();
                    ScenicProductEsDTO scenicProductEsDTO = JSON.parseObject(hit.getSourceAsString(), ScenicProductEsDTO.class);
                    if(scenicProductEsDTO != null){
                        popularProductList.setProductId(scenicProductEsDTO.getProductId());
                        popularProductList.setTitle(scenicProductEsDTO.getProductName());
                        popularProductList.setPrice(scenicProductEsDTO.getCostPrice());

                        popularProductList.setExchangeRate(scenicProductEsDTO.getExchangeRate());
                        BigDecimal price = null;
                        //成本乘以倍数，加上服务费，加上加服
                        Double rate = scenicProductEsDTO.getExchangeRate();
                        List<ScenicProductCostStrategySpecStock> stocksObj = scenicProductCostStrategySpecStockMapper.quertCostPriceByid(scenicProductEsDTO.getProductId());
                        if (!Objects.isNull(stocksObj.get(0).getCostPrice())){
                            price = stocksObj.get(0).getCostPrice();
                            popularProductList.setCostAmount(price);
                        }



                        BigDecimal mone = price.multiply(BigDecimal.valueOf(rate));
                        //BigDecimal moneAttr = mone.add(scenicProductEsDTO.getAmount()).setScale(0,BigDecimal.ROUND_UP);
                        /*popularProductList.setMoney(moneAttr
                                .add(scenicProductEsDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP)));*/
                        BigDecimal pcAmount = null;
                        BigDecimal appAmount = null;
                        //查询加服
                        List<ScenicProductChannelOnlineSelfPlatformDTO> platformObj = scenicProductChannelOnlineSelfPlatformMapper.selectByProductIdList(scenicProductEsDTO.getProductId());
                        if (!Objects.isNull(platformObj)){

                            for (ScenicProductChannelOnlineSelfPlatformDTO obj : platformObj){
                                if (obj.getChannelId().equals(ChannelMainData.APP_H5.getId())){

                                    BigDecimal jfPrice = new BigDecimal("0");
                                    // 加幅类型
                                    Integer adjustType = obj.getAdjustType();
                                    if(adjustType != null){
                                        if(adjustType.equals(1)){
                                            // 指定数值
                                            if(obj.getAmount() != null){
                                                jfPrice = jfPrice.add(obj.getAmount());
                                            }
                                        }else if(adjustType.equals(2)){
                                            // 百分比
                                            if(obj.getAmount() != null){
                                                jfPrice = jfPrice.add(mone.divide(obj.getAmount(), 0, BigDecimal.ROUND_UNNECESSARY).multiply(new BigDecimal("100")));
                                            }
                                        }
                                    }
                                    //加服
                                    appAmount = jfPrice;
                                    if (appAmount != null){
                                        popularProductList.setAmount(appAmount);
                                        BigDecimal moneAttr = (mone.add(appAmount)).setScale(0,BigDecimal.ROUND_UP);
                                        popularProductList.setAppMoney(moneAttr
                                                .add(scenicProductEsDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP)));
                                        popularProductList.setReserveCharge(scenicProductEsDTO.getReserveCharge());
                                    }else if (appAmount == null){
                                        popularProductList.setAppMoney(mone.setScale(0,BigDecimal.ROUND_UP)
                                                .add(scenicProductEsDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP)));
                                        popularProductList.setReserveCharge(scenicProductEsDTO.getReserveCharge());
                                    }

                                }else if (obj.getChannelId().equals(ChannelMainData.CHINA_TRAVEL.getId())){
                                    BigDecimal jfPrice = new BigDecimal("0");
                                    // 加幅类型
                                    Integer adjustType = obj.getAdjustType();
                                    if(adjustType != null){
                                        if(adjustType.equals(1)){
                                            // 指定数值
                                            if(obj.getAmount() != null){
                                                jfPrice = jfPrice.add(obj.getAmount());
                                            }
                                        }else if(adjustType.equals(2)){
                                            // 百分比
                                            if(obj.getAmount() != null){
                                                jfPrice = jfPrice.add(mone.divide(obj.getAmount(), 0, BigDecimal.ROUND_UNNECESSARY).multiply(new BigDecimal("100")));
                                            }
                                        }
                                    }
                                    pcAmount = jfPrice;
                                    if (pcAmount != null){
                                        BigDecimal moneAttr = (mone.add(pcAmount)).setScale(0,BigDecimal.ROUND_UP);
                                        popularProductList.setPcMoney(moneAttr
                                                .add(scenicProductEsDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP)));

                                    }else if (pcAmount == null){
                                        popularProductList.setPcMoney(mone.setScale(0,BigDecimal.ROUND_UP)
                                                .add(scenicProductEsDTO.getReserveCharge().setScale(0,BigDecimal.ROUND_UP)));
                                    }
                                    popularProductList.setReserveCharge(scenicProductEsDTO.getReserveCharge());

                                }
                            }
                        }





                        {// 解析图片
                            String photosJson = scenicProductEsDTO.getPhotosJson();
                            if(photosJson != null){
                                List<JSONObject> jsonObjects = JSON.parseArray(photosJson, JSONObject.class);
                                if(jsonObjects != null && jsonObjects.size() > 0){
                                    JSONObject jsonObject = jsonObjects.get(0);
                                    String url = jsonObject.getString("url");
                                    if(url != null){
                                        popularProductList.setPng(url);
                                    }
                                }
                            }
                        }
                        popularList.add(popularProductList);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.success(scenicProductIndexDTO);
    }

    public SearchResponse search(
            Map<String, Object> fuzzyMap,
            Map<String, Object> matchMap,
            Integer pageNum, Integer pageSize
    ){
        SearchRequest searchRequest = new SearchRequest(ElasticSearchConstant.SCENIC);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.from(pageNum);
        searchSourceBuilder.size(pageSize);
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        {// 模糊匹配
            if(fuzzyMap != null && fuzzyMap.size() > 0){
                Iterator<Map.Entry<String, Object>> iterator = fuzzyMap.entrySet().iterator();
                while(iterator.hasNext()){
                    Map.Entry<String, Object> next = iterator.next();
                    if(next.getValue() != null){
                        boolQueryBuilder.filter(QueryBuilders.fuzzyQuery(next.getKey(), next.getValue()));
                    }
                }
            }
        }

        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            return search;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
